package com.wei.czz.framework.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.wei.czz.common.enums.CommonEnum;
import com.wei.czz.common.enums.admin.menu.MenuTypeEnum;
import com.wei.czz.common.po.RolePo;
import com.wei.czz.common.po.UserPo;
import com.wei.czz.common.utils.SecurityUtils;
import com.wei.czz.framework.admin.dao.UserRoleDao;
import com.wei.czz.framework.admin.entity.UserEntity;
import com.wei.czz.framework.admin.entity.UserRoleEntity;
import com.wei.czz.framework.admin.service.UserRoleService;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.*;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

/**
 * Created by IntelliJ IDEA.
 *
 * @author wei
 * date: 2021-03-15 10:28:45
 * className: UserRoleServiceImpl 用户和角色关联操作请求服务接口实现类
 * version: 1.0
 * description:
 */
@Service("userRoleService")
@AllArgsConstructor
public class UserRoleServiceImpl extends ServiceImpl<UserRoleDao, UserRoleEntity> implements UserRoleService {

    private static final Logger log = LoggerFactory.getLogger(UserRoleServiceImpl.class);

    @Transactional
    @Override
    public void batchSave(List<UserRoleEntity> userRoleList) {
        boolean bool = this.saveBatch(userRoleList);
        log.info("批量添加用户关联角色完成。size={} bool={}", userRoleList.size(), bool);
    }

    @Override
    public List<UserRoleEntity> getList(List<Long> idList) {
        if (CollectionUtils.isEmpty(idList)) {
            log.info("获取用户与角色关联列表，传递的主键列表为空");
            return Collections.emptyList();
        }

        LambdaQueryWrapper<UserRoleEntity> userRoleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userRoleLambdaQueryWrapper.in(UserRoleEntity::getId, idList)
                .eq(UserRoleEntity::getDeleteStatus, CommonEnum.ZERO.getValue());
        // 查询
        List<UserRoleEntity> userRoleList = baseMapper.selectList(userRoleLambdaQueryWrapper);
        log.info("查询用户与角色关联完成。list.size={}", userRoleList.size());
        return userRoleList;
    }

    @Override
    public List<String> getRoleIdList(Long userId) {
        return baseMapper.getRoleIdList(userId, CommonEnum.ZERO.getValue());
    }

    @Override
    public List<RolePo> findUserPermitList(Long userId) {
        // 如果用户是系统用户，则查询该用户被赋予的操作权限
        List<RolePo> rolePoList = baseMapper.selectUserPermitList(userId, MenuTypeEnum.BUTTON_TYPE.getValue());
        log.info("查询用户权限列表完成。list.size={}", rolePoList.size());
        return rolePoList;
    }

    @Override
    public List<UserRoleEntity> findList(Long userId, Long roleId, Integer deleteStatus) {
        if (ObjectUtils.allNull(userId, roleId)) {
            log.info("查询用户与角色关联数据，传入的用户主键和角色为空");
            return Collections.emptyList();
        }
        LambdaQueryWrapper<UserRoleEntity> userRoleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userRoleLambdaQueryWrapper.eq(Objects.nonNull(userId), UserRoleEntity::getUserId, userId)
                .eq(Objects.nonNull(roleId), UserRoleEntity::getRoleId, roleId)
                .eq(Objects.nonNull(deleteStatus), UserRoleEntity::getDeleteStatus, CommonEnum.ZERO.getValue());
        // 查询数据
        List<UserRoleEntity> userRoleList = baseMapper.selectList(userRoleLambdaQueryWrapper);
        log.info("查询用户关联角色数据完成。userId={} roleId={} deleteStatus={} size={}", userId, roleId, deleteStatus,
                userRoleList.size());
        return userRoleList;
    }

    @Override
    public Set<Long> getUserIdSet(Long roleId) {
        return baseMapper.getUserIdSet(roleId, CommonEnum.ZERO.getValue());
    }

    @Override
    public List<UserEntity> getUserList(Long roleId) {
        List<UserEntity> userList = baseMapper.selectUserList(roleId, CommonEnum.ZERO.getValue());
        if (userList.isEmpty()) {
            log.info("角色关联用户列表为空。roleId={}", roleId);
        }
        return userList;
    }

    @Override
    public List<UserRoleEntity> findUserRoleList(List<Long> userIdList, List<Long> roleIdList,
                                                 List<Integer> relationModeList) {
        if (CollectionUtils.isEmpty(userIdList) && CollectionUtils.isEmpty(roleIdList) &&
                CollectionUtils.isEmpty(relationModeList)) {
            log.info("查询用户与角色关联数据，参数传递的用户主键列表、角色主键列表和关联模式列表均为空");
            return Collections.emptyList();
        }
        LambdaQueryWrapper<UserRoleEntity> userRoleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userRoleLambdaQueryWrapper.in(!CollectionUtils.isEmpty(userIdList), UserRoleEntity::getUserId, userIdList)
                .in(!CollectionUtils.isEmpty(roleIdList), UserRoleEntity::getRoleId, roleIdList)
                .in(!CollectionUtils.isEmpty(relationModeList), UserRoleEntity::getRelationMode, relationModeList)
                .eq(UserRoleEntity::getDeleteStatus, CommonEnum.ZERO.getValue());
        // 查询
        List<UserRoleEntity> userRoleList = baseMapper.selectList(userRoleLambdaQueryWrapper);
        log.info("查询用户关联角色完成。size={}", userRoleList.size());
        return userRoleList;
    }

    @Transactional
    @Override
    public void batchUpdate(List<UserRoleEntity> userRoleList) {
        boolean bool = this.updateBatchById(userRoleList);
        log.info("批量修改用户关联角色完成。size={} bool={}", userRoleList.size(), bool);
    }

    @Override
    public void deleteUserRole(List<Long> userIdList, List<Long> roleIdList) {
        // 获取操作用户
        UserPo userPo = SecurityUtils.getUser();
        Date date = new Date();
        log.info("用户（{}）操作删除用户与角色关联关系：userIdList={} roleIdList={}", userPo.getUserId(), userIdList,
                roleIdList);

        LambdaUpdateWrapper<UserRoleEntity> userRoleLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        // 设置 删除状态、删除时间和操作删除的用户 字段值
        userRoleLambdaUpdateWrapper.set(UserRoleEntity::getDeleteStatus, CommonEnum.ONE.getValue())
                .set(UserRoleEntity::getUpdateTime, date)
                .set(UserRoleEntity::getUpdateUser, userPo.getUsername())
                .set(UserRoleEntity::getUpdateUserId, userPo.getUserId());
        // 匹配 用户主键、角色主键和删除状态 字段
        userRoleLambdaUpdateWrapper.in(!CollectionUtils.isEmpty(userIdList), UserRoleEntity::getUserId, userIdList)
                .in(!CollectionUtils.isEmpty(roleIdList), UserRoleEntity::getRoleId, roleIdList)
                .eq(UserRoleEntity::getDeleteStatus, CommonEnum.ZERO.getValue());
        // 操作数据库用户与角色关联表，批量删除角色与用户的关联关系
        int count = baseMapper.update(null, userRoleLambdaUpdateWrapper);
        log.info("批量删除角色关联用户数据结果：count={}", count);
    }

    @Override
    public void unassociatedUserRole(List<Long> relationIdList) {
        // 获取操作用户
        UserPo userPo = SecurityUtils.getUser();
        Date date = new Date();

        LambdaUpdateWrapper<UserRoleEntity> userRoleLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        // 设置 删除状态、删除时间和操作删除的用户 字段值
        userRoleLambdaUpdateWrapper.set(UserRoleEntity::getDeleteStatus, CommonEnum.ONE.getValue())
                .set(UserRoleEntity::getUpdateTime, date)
                .set(UserRoleEntity::getUpdateUser, userPo.getUsername())
                .set(UserRoleEntity::getUpdateUserId, userPo.getUserId());
        // 匹配 用户主键、角色主键和删除状态 字段
        userRoleLambdaUpdateWrapper.in(UserRoleEntity::getId, relationIdList)
                .eq(UserRoleEntity::getDeleteStatus, CommonEnum.ZERO.getValue());
        // 操作数据库用户与角色关联表，批量删除角色与用户的关联关系
        int count = baseMapper.update(null, userRoleLambdaUpdateWrapper);
        log.info("批量删除用户关联角色数据结果：count={}", count);
    }

}